import {useRef,useCallback,useEffect,useLayoutEffect,useState} from 'react'
import '../../../assets/Work/Picture/picture.scss'
interface Position{
  x:number
  y:number
}
function Picture(props:any) {
  const [position,setPosition]=useState<Position>({x:0,y:0});
  const ref=useRef<HTMLDivElement>(null);
  const [rotation,setRotation]=useState(0);
  const [scale,setScale]=useState(1)
  const initialPosition={x:0,y:0};
const handleMouseDown=useCallback((e:React.MouseEvent<HTMLDivElement,MouseEvent>)=>{
  const {clientX,clientY}=e;
  initialPosition.x=clientX-position.x;
  initialPosition.y=clientY-position.y


  document.addEventListener('mousemove',handleMouseMove);
  document.addEventListener('mouseup',handleMouseUp)

},[position])

const handleMouseMove=(e:MouseEvent)=>{
  const {clientX,clientY}=e;
  setPosition({
    x:clientX-initialPosition.x,
    y:clientY-initialPosition.y
  })
}
// 移动鼠标移动和释放事件的监听器
const handleMouseUp=()=>{
  document.removeEventListener('mousemove',handleMouseMove)
  document.removeEventListener('mouseup',handleMouseUp)
}

useLayoutEffect(()=>{
  const node=ref.current;
  if(node){
    node.addEventListener('mousedown',handleMouseDown);

    return ()=>{
      node.removeEventListener('mousedown',handleMouseDown)
    }
  }
},[handleMouseDown])

// 旋转
const handdleRotate=()=>{
  setRotation((prevRotation)=>prevRotation+60)
}
const handleZoom=(e:any)=>{
  const newScale=Math.min(Math.max(0.5,scale+e.deltaY * -0.001),3)
  setScale(newScale)
}

let content;
switch(props.element.component){
  case 'Dimg':
    content=<img draggable={false} src={props.element.propLable} alt="" />
    break;
    default:
      content=null;
}

  return (
    <div className='drawing-wrap'>
    <div className='drawing-item'  ref={ref}
      style={
        {
          position:'absolute',
          left:`${position.x}px`,
          top:`${position.y}px`,
          cursor:'grab',
          // width:'100px',
          // height:'100px',
          // backgroundColor:'lightblue',
          transform:`rotate(${rotation}deg) scale(${scale})`
        }
      }
      onWheel={handleZoom}
      >
     {content}
     <button onClick={handdleRotate}>旋转</button>
    </div>
    </div>
  )
}

export default Picture
